import os
import sys
import platform
import signal
import time
import yaml

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))
from log_info import logger


def get_yaml(path):
    try:
        with open(path, 'r', encoding='utf-8') as f:
            return yaml.load(f, Loader=yaml.FullLoader)
    except Exception as e:
        logger.info('{} not found'.format(path))
        logger.info(e)
        return None


def pas():
    pass


def string_to_chunks(s, chunk_size):
    return [s[i:i + chunk_size] for i in range(0, len(s), chunk_size)]


def kill_other_python(pid=None):
    import psutil  # 用于获取系统进程信息
    pid_me = os.getpid()  # 获取当前进程的PID
    # logger.info("my pid ", pid_me, type(pid_me))
    python_processes = []  # 创建一个空列表，用于存储其他Python进程的信息
    for proc in psutil.process_iter(['pid', 'name', 'cmdline']):  # 遍历系统中所有进程的迭代器，获取进程的PID、名称和命令行参数
        try:
            if 'python' in proc.info['name'].lower() and len(proc.info['cmdline']) > 1 and len(
                    proc.info['cmdline'][1]) < 30:
                python_processes.append(proc.info)
        # 出现异常的时候捕获 不存在的异常，权限不足的异常， 僵尸进程
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass
    if pid is None:
        for process in python_processes:
            # logger.info(f"PID: {process['pid']}, Name: {process['name']}, Cmdline: {process['cmdline']}")
            # logger.info("this", process['pid'], type(process['pid']))
            if int(process['pid']) != pid_me:
                if 'Windows' in platform.platform():
                    os.kill(int(process['pid']), signal.SIGTERM)
                else:
                    os.kill(int(process['pid']), signal.SIGKILL)  # 如果当前进程的PID不等于自身的PID，则发送 SIGKILL 信号杀死该进程
                logger.info(f"杀死了进程{process['name']}{process['pid']}")
                time.sleep(0.3)
    else:
        if 'Windows' in platform.platform():
            os.kill(pid, signal.SIGTERM)
        else:
            os.kill(pid, signal.SIGKILL)
        logger.info(f"杀死了进程{pid}")
        time.sleep(0.3)